import React from 'react';
import {createStore} from 'redux';
import {Provider, connect} from 'react-redux';

import OperatorList from './OperatorList'
import OperatorEdit from './OperatorEdit'

import './Operator.css';





//action
const changeTextAction = {
  type:'CHANGE_TEXT'
}
const buttonClickAction = {
  type:'BUTTON_CLICK'
}

//reducer
const initialState = {
  text: 'Hello'
}
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'CHANGE_TEXT':
      return {
        text: state.text=='Hello' ? 'world':'Hello'
      }
    case 'BUTTON_CLICK':
      return {
        text: 'Hello world'
      }
    default:
      return initialState;
  }
}

//store
let store = createStore(reducer);

//映射Redux state到组件的属性
function mapStateToProps(state) {
  return { text: state.text }
}

//映射Redux actions到组件的属性
function mapDispatchToProps(dispatch){
  return{
    onButtonClick:()=>dispatch(buttonClickAction),
    onChangeText:()=>dispatch(changeTextAction)
  }
}

//连接组件
const VisibleOperatorList = connect(mapStateToProps, mapDispatchToProps)(OperatorList)









class Operator extends React.Component {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this);
    this.state = {
      shown: 'list'
    }
  }

  render() {
    return (
      <Provider store={store}>
        <div>
          <h1 onClick={this.handleClick}>operators</h1>
          <div className={this.state.shown=='list' ? '' : 'hide'}>
            <VisibleOperatorList ref="operatorlist"/>
          </div>
          <div className={this.state.shown=='edit' ? '' : 'hide'}>
            <OperatorEdit ref="operatoredit"/>
          </div>
        </div>
      </Provider>
    )
  }

  componentDidMount() {

  }

  handleClick() {
    console.log(this.refs);
    if(this.state.shown == 'list')
      this.setState({shown: 'edit'})
    else
      this.setState({shown: 'list'})
  }
}

export default Operator;